package com.xsz.pda.device.qrcode

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import java.lang.ref.WeakReference

//二维码读取
class QrcodeReader(private val activity: WeakReference<Activity>) {

    interface OnScanListener { fun onScan(qrcode: String) }

    private var onReadListener: OnScanListener? =  null

    private val scanResultReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            intent.getStringExtra("string")?.trim()?.let {
                onReadListener?.onScan(it)
            }
        }
    }

    fun setOnScanListener(onScanListener: OnScanListener) {
        onReadListener = onScanListener
    }

    fun init() {
        val intentFilter = IntentFilter("com.uc.scanner.result")
        activity.get()?.registerReceiver(scanResultReceiver, intentFilter)
    }

    fun release() {
        activity.get()?.unregisterReceiver(scanResultReceiver)
    }

}